#include <stdint.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <poll.h>

/**
 *
 */
static int fd;
void* poll01(void *ptr) {
	int ret;
	char *buf = (char*) calloc(1024, sizeof(char));
	fd = open("/dev/t01", O_RDWR, O_NONBLOCK);
	if (fd < 0) {
		perror("open");
		printf("error open\n");
		exit(EXIT_FAILURE);
	}

	struct pollfd fds[1];
	fds[0].fd = fd;
	fds[0].events = POLLIN;
	fds[0].revents = 0;
	while (1) {
		printf("start poll\n");
		ret = poll(fds, 1, -1);
		if (ret == -1) {
			perror("poll test");
			return NULL;
		}
		if (fds[0].revents & POLLIN) {
			ret = read(fds[0].fd, buf, 1024);
			if (ret < 0) {
				perror("read test");
				return NULL;
			}
			buf[ret] = '\0';
			printf("read: %s\n", buf);
		}
		sleep(1);
	}
	close(fd);
	return NULL;
}

void* read01(void *ptr) {
	char *buf = (char*) calloc(1024, sizeof(char));
	int fd = open("/dev/t01", O_RDWR);
	int ret = read(fd, buf, 1024);
	if (ret == -1) {
		perror("poll test  000 ");
		return NULL;
	}
	return NULL;
}

//static void  read01(int fd){
//	char buf[1024];
//		int len = read(fd, buf, 1024);
//		buf[len] = '\0';
//		printf("read: %s\n", buf);
//}

void* write01(void *ptr) {
	fd = open("/dev/t01", O_RDWR, O_NONBLOCK);
	while (1) {
		char *buf =
				"kfifo_from_user - puts some data from user space into the fifo;";
		//	printf("2 0\n");
		write(fd, buf, strlen(buf));
		sleep(1);
	}

//	printf("2 1\n");
//	read01(fd);
	close(fd);
	return NULL;
}

void* ioctl01(void *ptr) {
	fd = open("/dev/t01", O_RDWR, O_NONBLOCK);
	if (fd < 0) {
		perror("open");
		printf("error open\n");
		return NULL;
	}
	while (1) {
		ioctl(fd, 0, 100);
		sleep(3);
		ioctl(fd, 1, 100);
		sleep(2);
	}
	close(fd);
	return NULL;
}

int main() {
	pthread_t thread;
//	pthread_t thread2;
	pthread_create(&thread, NULL, ioctl01, NULL);
	sleep(2);
//	pthread_create(&thread2, NULL, write01, NULL);
	pthread_join(thread, NULL);
//	pthread_join(thread2, NULL);
	printf("main exit\n");
	return EXIT_SUCCESS;
}

